﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MediaGarden.Playlists.Services;
using Orchard.ContentManagement;
using Downplay.Mechanics.Models;
using Downplay.Mechanics.Services;
using Orchard.Environment.Extensions;
using Orchard;
using MediaGarden.Models;
using MediaGarden.Playlists.Mechanical.Models;

namespace MediaGarden.Playlists.Mechanical.Services
{
    public class MechanicalPlaylistBuilder : IPlaylistStorageProvider
    {
        private readonly IMechanicsService _mechanics;
        public IOrchardServices Services { get; set; }
        public MechanicalPlaylistBuilder(
            IOrchardServices services,
            IMechanicsService mechanicsService
            )
        {
            Services = services;
            _mechanics = mechanicsService;
        }

        public void PlaylistLoading(PlaylistContext context)
        {
            // TODO: How will Preview function??
            var media = context.MediaItem as IContent;
            if (media != null)
            {
                var playlistItems = _mechanics.Connectors(media, "PlaylistItem").Join<SequencePartRecord>().OrderBy(s => s.Sequence).ForPart<PlaylistItemPart>();
                foreach (var item in playlistItems.List())
                {
                    var rightItem = Services.ContentManager.Get<MediaPart>(item.As<ConnectorPart>().RightContentItemId);
                    if (rightItem!=null)
                        context.Items.Add(rightItem);
                }
            }
        }

        public void PlaylistLoaded(PlaylistContext context)
        {
        }

        public void PlaylistStoring(PlaylistContext context)
        {
            // Get left content item
            var leftItem = context.MediaItem as IContent;
            if (leftItem == null) return;
            var leftSocket = leftItem.As<SocketsPart>();
            if (leftSocket == null) return;

            foreach (var item in context.Items)
            {
                // Right item
                var rightItem = item as IContent;
                if (rightItem == null) continue;
                var rightSocket = rightItem.As<SocketsPart>();
            }

            // TODO: This isn't finished
        }

        public void PlaylistStored(PlaylistContext context)
        {
        }
    }
}